package com.tool.permission.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.tool.permission.SecurityManager;
import com.tool.permission.annotation.NotPermission;
import com.tool.permission.subject.WebSubject;
import com.tool.permission.util.SecurityUtils;
import com.tool.permission.util.URLMatcher;

/**
 * 权限验证
 * @author huff
 *
 */
public class AccessInterceptor extends HandlerInterceptorAdapter{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if(handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
			NotPermission permission = method.getAnnotation(NotPermission.class);
			if (permission != null) {
				return true;
			}
		
			String uri = request.getRequestURI().replaceFirst(request.getContextPath(), "");
			int index = uri.indexOf("?");
			if(index != -1) {
				uri = uri.substring(0, index);
			}
			
			index = uri.indexOf(";jsessionid");
			if(index != -1) {
				uri = uri.substring(0, index);
			}
			SecurityManager securityManager = SecurityUtils.getSecurityManager();
			//判断是否不要验证
			List<String> excludes = securityManager.getExcludes();
			if(CollectionUtils.isNotEmpty(excludes)) {
				for (String exclude : excludes) {
					if(URLMatcher.match(exclude, uri)) {
						return true;
					}
				}
			}
			WebSubject subject = SecurityUtils.getWebSubject(request);
			if(subject.isPermitted(uri)) {
				return true;
			}
			String page = securityManager.getFailPage();
			if(StringUtils.isNotEmpty(page)) {
				response.sendRedirect(request.getContextPath() + page);
			} else {
				response.setStatus(HttpStatus.UNAUTHORIZED.value());
				response.setCharacterEncoding("UTF-8");  
				response.setContentType("application/json; charset=utf-8");  
				PrintWriter out=null;
				try {  
				    out = response.getWriter();  
				    out.append("{\"code\":4001,\"message\":\"没有该url的该问权限\"}");  
				} catch (IOException e) {  
				    e.printStackTrace();
				}finally{
				    if (out != null){
				        out.close(); 
				    }  
				}  
			}
		}
		return false;
	}
}
